package com.tanhua.server.service.impl;

import com.github.dozermapper.core.Mapper;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Announcement;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.MessagesService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wjs
 * @version 1.0
 * @date 2021/12/29 0029 上午 11:45
 */

@Service
public class MessagesServiceImpl implements MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private AnnouncementsApi announcementsApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private Mapper mapper;

    /**
     * 根据环信id查询用户详情
     */
    @Override
    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
//        //1、根据环信id查询用户
//        User user = userApi.findByHuanxin(huanxinId);
//        //2、根据用户id查询用户详情
//        UserInfo userInfo = userInfoApi.findById(user.getId());
        Long userId = Long.valueOf(huanxinId.substring(2));
        System.out.println(userId);
        UserInfo userInfo = userInfoApi.findById(userId);

        UserInfoVo vo = mapper.map(userInfo, UserInfoVo.class);
        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    @Override
    public void contacts(Long friendId) {
        Long userId = UserHolder.getUserId();

        //将好友关系注册到环信
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + userId, Constants.HX_USER_PREFIX + friendId);
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }

        //如果注册成功，记录好友关系到mongodb
        friendApi.save(userId, friendId);
    }

    @Override
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        List<Friend> friends = friendApi.findPage(UserHolder.getUserId(), page, pagesize);
        if (friends == null || friends.isEmpty()) {
            return new PageResult();
        }

        List<Long> userIds = friends.stream().map(friend -> friend.getFriendId()).collect(Collectors.toList());
        UserInfo info = new UserInfo();
        info.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, info);
        List<ContactVo> vos = friends.stream().filter(friend -> map.get(friend.getFriendId()) != null)
                .map(friend -> ContactVo.init(map.get(friend.getFriendId())))
                .collect(Collectors.toList());

        return new PageResult(page, pagesize, 0L, vos);
    }

    @Override
    public PageResult announcements(Integer page, Integer pagesize) {
        List<Announcement> list = announcementsApi.findPage(page, pagesize);
        Long count = announcementsApi.findCount();

        return new PageResult(page, pagesize, count, list);
    }

    @Override
    public PageResult messagesPageByType(Integer page, Integer pagesize, CommentType type) {
        PageResult result = commentApi.messagesPageByType(page, pagesize, type.getType(), UserHolder.getUserId());

        List<Comment> items = (List<Comment>) result.getItems();

        //获取被喜欢,被评论,被点赞用户id集合
        List<Long> ids = items.stream().map(item -> item.getUserId()).collect(Collectors.toList());
        if(ids.isEmpty()){
//            throw new BusinessException(ErrorResult.messagesError());
            return null;
        }

        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);

        List<CommentVo> vos = items.stream().filter(comment -> map.get(comment.getUserId()) != null)
                .map(comment -> CommentVo.init(map.get(comment.getUserId()), comment))
                .collect(Collectors.toList());

        result.setItems(vos);

        return result;
    }
}
